package com.boxing.servlet;

import com.boxing.bean.User;
import com.boxing.bean.UserDesc;
import com.boxing.service.UserService;
import com.boxing.utils.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "UploadServlet", value = "/login/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("sss");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean login = WebUtil.isLogin(request);
        if (login){
            // 找到对应的用户
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("token");
            String name = user.getUser();

            Part partFile = request.getPart("fileName");
            // 获取上传的文件名
            String fileName = partFile.getSubmittedFileName();
            if (fileName == null || fileName.length() == 0){
                response.sendRedirect( request.getContextPath()+"/index.jsp");
                return;
            }
            // 获取文件的后缀名
            int endIndex = fileName.lastIndexOf('.');
            String fileEnd = fileName.substring(endIndex);
            String iconFileName = name+ "-"+new Date().getTime() +fileEnd;
            // 将文件保存在项目的 /userIcon 目录下,可供浏览器访问
            File file = new File("C:\\Users\\23243\\Desktop\\StuManager\\web\\userIcon\\" + iconFileName);
            // 将part中的数据写出到指定的文件中
            String fileAbsolutePath = file.getAbsolutePath();
            partFile.write(fileAbsolutePath);

            // 将保存的文件路径存储到数据库中
            UserDesc userDesc = new UserDesc();
            userDesc.setName(name);
            String serverPath = WebUtil.getServerPath(request);
            String iconUrl = serverPath + "userIcon/" +iconFileName;
            userDesc.setIcon(iconUrl);
            boolean isEdit = userService.editIcon(userDesc);
            if (isEdit){
                // 上传头像成功 将页面重定向到首页
                System.out.println("上传成功后文件存放的地址:"+ iconUrl);
            }else {

            }
            response.sendRedirect( request.getContextPath()+"/index.jsp");
        }

    }
}
